#!/usr/bin/env bash

requirements_netbsd_lib_installed()
{
  [[ -f /etc/mtree/set.$1 ]] || return $?
}

requirements_netbsd_libs_install()
{
  \typeset _set_base_url _set _set_url _set_md5
  _set_base_url="http://ftp.netbsd.org/pub/NetBSD/NetBSD-${_system_version_full}/${_system_arch/x86_64/amd64}/binary/sets"
  for _set in "$@"
  do
    _set_url="${_set_base_url}/${_set}.tgz"
    _set_md5="$(__rvm_curl -s ${_set_base_url}/MD5 | __rvm_grep "(${_set}.tgz)" | __rvm_awk '{print $NF}')"
    __rvm_curl ${_set_url} -o ${rvm_archives_path}/${_set}.tgz || return $?
    [[ "$(__rvm_md5_calculate ${rvm_archives_path}/${_set}.tgz)" == ${_set_md5} ]] ||
      {
        \typeset result=$?
        rvm_error "Set checksum verification failed"
        return $result
      }
    __rvm_try_sudo tar xzf ${rvm_archives_path}/${_set}.tgz -C / || return $?
  done
}

requirements_netbsd_check_custom()
{
  \typeset _lib
  for _lib in "$@"
  do
    [[ " ${packages_custom[*]} " == *" ${_lib} "* ]] ||
    requirements_netbsd_custom_lib_installed "${_lib}" ||
    __rvm_add_once packages_custom "${_lib}"
  done
}

requirements_netbsd_custom_lib_installed()
{
  pkg_info -qE "$1" || return $?
}

requirements_netbsd_install_custom()
{
  __rvm_try_sudo \
    PKG_PATH="http://ftp.netbsd.org/pub/pkgsrc/packages/NetBSD/amd64/${_system_version}/All/" \
    pkg_add "$@" || return $?
}

requirements_netbsd_after()
{
  \typeset _certs
  _certs="$(ls /etc/openssl/certs)"
  [[ ! -n "${certs}" && -f /etc/ssl/certs/ca-certificates.crt ]] ||
    __rvm_try_sudo mozilla-rootcerts install >/dev/null 2>&1 || return $?
}

requirements_netbsd_define()
{
  case "$1" in
    (rvm)
      requirements_netbsd_check_custom bash curl mozilla-rootcerts p5-Digest-SHA
      ;;

    (jruby*)
      requirements_netbsd_check_custom openjdk7 make
      if
        is_head_or_disable_binary "$1"
      then
        case $( jruby_installation_method  "$1" ) in
          ant) __rvm_which ant >/dev/null || requirements_netbsd_check_custom apache-ant   ;;
          mvn) __rvm_which mvn >/dev/null || requirements_netbsd_check_custom apache-maven ;;
        esac
      fi
      ;;

    (ir*)
      true
      ;;

    (opal)
      true
      ;;

    (*-head)
      requirements_check comp
      requirements_netbsd_check_custom automake autoconf libtool bison gdbm libffi libyaml scmgit
      __rvm_update_configure_opt_dir "$1" "/usr/pkg"
      ;;

    (*)
      requirements_check comp
      requirements_netbsd_check_custom automake autoconf libtool bison gdbm libffi libyaml
      __rvm_update_configure_opt_dir "$1" "/usr/pkg"
      ;;
  esac
}
